package cn.hinglo.common.interceptors.security;

import cn.hinglo.common.annotation.IgnorePermission;
import cn.hinglo.common.config.error.ErrorConstant;
import cn.hinglo.common.config.error.SelfErrorRender;
import cn.hinglo.common.constant.SystemConstant;
import cn.hinglo.common.interceptors.base.BaseInterceptor;
import cn.hinglo.permission.service.UserPermission;
import cn.hinglo.permission.service.impl.UserPermissionImpl;
import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Inject;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;

/**
 * @createTime: 2018/3/5
 * @author: HingLo
 * @description: 权限管理拦截器
 */
@Slf4j
public class PermissionInterceptor extends BaseInterceptor {
    /***
     * 用户权限接口
     */
    @Inject(UserPermissionImpl.class)
    private UserPermission userPermission;


    @Override
    public void preHandle(HttpServletRequest request, HttpServletResponse response, Invocation inv) {
        String ctx = request.getContextPath();
        // 访问的完整连接
        String uri = request.getRequestURI();
        // 权限判定需要去掉访问的应用名称
        String url = StrUtil.isBlank(ctx) ? uri : StrUtil.removePrefix(uri, ctx);
        String userId = (String) request.getAttribute(SystemConstant.PERMISSION_USER_ID);
        if (StrKit.notBlank(userId) && userPermission.hasPermission(userId, url)) {
            inv.invoke();
        } else {
            SelfErrorRender.errorRender(ErrorConstant.ERROR403, inv.getController());
        }
    }


    /**
     * 排除拥有的指定的注解的方法
     *
     * @return 是否忽略
     */
    @Override
    public Class<? extends Annotation> ignoreAnnotation() {
        return IgnorePermission.class;
    }
}
